#pragma once
#include "parser.h"
#include <iostream>
#include <sstream>
#include <stack>
#include <map>
#include <vector>
#include <cctype>

using namespace std;

class CodeGenerator {
private:
    ostream& out;
    int labelCounter;
    stack<string> loopStartLabels;
    stack<string> loopEndLabels;
    stack<map<string, int>> symbolTables;
    map<string, int> currentSymbols;
    int stackOffset;
    string currentFunction;
    string currentReturnType;
    int paramCount;
    bool optimize;  // 新增优化标志

public:
    CodeGenerator(ostream& output = cout, bool opt = false);  // 修改构造函数
    void generate(CompUnitNode* node);
    string getGeneratedCode() const;

    // 新增优化方法
    void applyOptimizations(CompUnitNode* node);
    void optimizeFunction(FuncDefNode* node);
    void optimizeExpression(ExprNode* node);

private:
    void generateFunction(FuncDefNode* node);
    void generateStatement(StmtNode* node);
    void generateExpression(ASTNode* node);
    void enterScope();
    void exitScope();
    void declareVariable(const string& name);
    int getVariableOffset(const string& name);
    string newLabel();

    ostringstream codeStream;
};